package cn.wolfcode.controller;

import cn.wolfcode.config.CustomRealm;
import cn.wolfcode.domain.User;
import cn.wolfcode.service.IUserService;
import cn.wolfcode.utils.JsonResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/rbac")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private CustomRealm myShiroRealm;

    @PostMapping("/login")
    public Object login(User user){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getUsername(),
                user.getPassword()
        );
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return JsonResult.error(JsonResult.CODE_ERROR_PARAM,"系统异常","系统异常");
        } catch (AuthorizationException e) {
            e.printStackTrace();
        }
        return JsonResult.success();
    }
 
 
    /**
     * 注册用户
     * @return
     */
    @PostMapping("/user")
    public Object registerUser(User user){
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("name",user.getUsername());
        User one = userService.getOne(wrapper);
        if(!(one==null)){
            return JsonResult.error(JsonResult.CODE_ERROR_PARAM,"系统异常","系统异常");
        }
        if(StringUtils.isEmpty(user.getUsername())){
            return JsonResult.error(JsonResult.CODE_ERROR_PARAM,"系统异常","系统异常");
        }
        userService.save(user);
        return JsonResult.success();
    }
}